package com.lzh.log.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;

import java.text.MessageFormat;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhehen.lu
 * @date 2025/08/10 09:49
 */
public class MDCTraceUtil {
    public static final String TRACE_ID_HEADER = "x-traceId-header";
    public static final String SPAN_ID_HEADER = "x-spanId-header";
    public static final String TRACE_ID = "traceId";
    public static final String SPAN_ID = "spanId";
    public static final int FILTER_ORDER = -1;
    private static final TransmittableThreadLocal<AtomicInteger> spanNumber = new TransmittableThreadLocal();

    public MDCTraceUtil() {
    }

    public static void addTraceId() {
        String traceId = createTraceId();
        MDC.put("traceId", traceId);
        MDC.put("spanId", "0");
    }

    public static void putTraceId(String traceId, String spanId) {
        MDC.put("traceId", traceId);
        MDC.put("spanId", spanId);
    }

    public static String getTraceId() {
        return MDC.get("traceId");
    }

    public static String getSpanId() {
        return MDC.get("spanId");
    }

    public static void removeTraceId() {
        MDC.remove("traceId");
        MDC.remove("spanId");
    }

    public static String createTraceId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static String getNextSpanId() {
        return MessageFormat.format("{}.{}", getSpanId(), ((AtomicInteger)spanNumber.get()).incrementAndGet());
    }

    private static void initSpanNumber() {
        spanNumber.set(new AtomicInteger(0));
    }
}
